# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:30
@Auth： gubei
@File：AuthorizationMid.py
@IDE：PyCharm
@Description：身份验证中间件
"""

import re

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import Response


class AuthorizationMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    async def dispatch(
            self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:
        # 不进行身份校验的接口地址
        excluded_paths = [
            # API文档相关
            "/docs", "/redoc", "/openapi.json", 
            "/swagger-ui-bundle.js", "/swagger-ui.css", "/redoc.standalone.js",
            # 认证相关
            "/api/token", "/api/refresh", "/token", 
            # 用户相关
            "/api/user/login", "/api/user/register", "/api/user/forget",
            # 健康检查
            "/api/health",
            # 静态资源
            "/static",
            # WebSocket相关
            "/api/ws", "/ws"
        ]

        # 检查是否WebSocket请求（WebSocket路径可以通过）
        if request.url.path.startswith("/api/ws") or request.url.path.startswith("/ws"):
            return await call_next(request)

        # 检查请求路径是否在排除列表中
        for excluded_path in excluded_paths:
            if request.url.path.startswith(excluded_path):
                return await call_next(request)

        return await call_next(request)
